package com.sohu.sip.cds.taskqueue;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

import com.sohu.peak.gallery.domain.Category;
import com.sohu.peak.util.ConfigManager;
import com.sohu.peak.util.Logger;

/**
 * Created by IntelliJ IDEA. User: gangma Date: 2008-7-7 Time: 17:24:54
 */
public class LinkedEventQueue implements CdsEventQueue {
	private static final Logger log = new Logger();
	LinkedBlockingQueue<CdsEvent> linkedBlockingQueue;

	public LinkedEventQueue() {
		int queueSize = ConfigManager.instance().getIntProperty("cds", "queue.size");

		if (queueSize <= 0) {
			queueSize = 2000;
		}

		this.linkedBlockingQueue = new LinkedBlockingQueue<CdsEvent>(queueSize);
	}

	public boolean push(Long id, RenderType renderType, RenderOperateType renderOperateType,
			String businessCode) {
		CdsEvent cdsEvent = new CdsEvent(renderType, renderOperateType, id, businessCode);
		return this.push(cdsEvent);
	}

	public boolean push(Long id, RenderType renderType, RenderOperateType renderOperateType,
			String businessCode,Category cate) {
		CdsEvent cdsEvent = new CdsEvent(renderType, renderOperateType, id, businessCode,cate);
		return this.push(cdsEvent);
	}
	
	public boolean push(CdsEvent cdsEvent) {
		log
				.debug(
						"[QueueSize:%s] Push cdsEvent:renderId=%s,renderOperateType=%s,renderType=%s,businessCode=%s,category.id=%s",
						linkedBlockingQueue.size(), cdsEvent.getRenderId(),
						cdsEvent.getRenderOperateType(), cdsEvent
								.getRenderType(), cdsEvent.getBusinessCode(),
						cdsEvent.getCategory() != null ? cdsEvent.getCategory()
								.getId() : "");
		return linkedBlockingQueue.offer(cdsEvent);
	}

	public CdsEvent poll() {
		return this.linkedBlockingQueue.poll();
	}

	public List<CdsEvent> poll(int size) {
		List<CdsEvent> list = new ArrayList<CdsEvent>(size);

		for (int i = 0; i < size; i++) {
			CdsEvent event = linkedBlockingQueue.poll();
			if (event == null) {
				break;
			} else {
				log
						.debug(
								"[QueueSize:%s] Poll cdsEvent:renderId=%s,renderOperateType=%s,renderType=%s,businessCode=%s,category.id=%s",
								linkedBlockingQueue.size(),
								event.getRenderId(), event
										.getRenderOperateType(), event
										.getRenderType(), event
										.getBusinessCode(),
								event.getCategory() != null ? event
										.getCategory().getId() : "");
				list.add(event);
			}
		}
		return list;
	}
}